<!--
 * @Description: 组织人员-岗位设置
 * @Author: xinqiao lxq1990.0716@qq.com
 * @Date: 2024-03-05
 * @LastEditors: xinqiao lxq1990.0716@qq.com
 * @LastEditTime: 2024-03-28
-->
<template>
  <div class="leader">
    <a-modal v-model:visible="visible" title="岗位设置" :width="600" @ok="onOk">
      <div class="title">{{ props.data.userName }}在 “ {{ props.data.depts.join('>') }} ” 的岗位</div>
      <div class="search">
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-item label="岗位">
              <a-input v-model:value="searchParam.positionName" placeholder="请输入" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-button type="primary" @click="search()">查询</a-button>
          </a-col>
        </a-row>
      </div>
      <div class="list">
        <a-table :columns="columns" :data-source="dataList" :loading="loading" :pagination="pagination" @change="onPaginationChange">
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'action'">
              <span @click="add(record)">
                <a>添加</a>
              </span>
            </template>
          </template>
        </a-table>
      </div>
      <div class="result">
        <div class="result-empty" v-if="results.length === 0">请先添加岗位</div>
        <a-tag closable @close.prevent="removeResult(i)" class="result-item" v-for="(item, i) in results" :key="`result-item${i}`"> {{ item.positionName }}</a-tag>
      </div>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import { message } from 'ant-design-vue'
  import { computed, reactive, ref, watch } from 'vue'

  import { requestPositionList, requestSavePositionUser } from '/@/api/business/company/position'
  import { HttpCodeEnum } from '/@/enums/httpEnum'
  import { useQueryPagination } from '/@/hooks/useQueryPagination'
  import { getCompanyInfo } from '/@/storage'

  const { companyId } = getCompanyInfo()

  const props = defineProps({
    visible: { type: Boolean, default: false },
    depts: { type: Array, default: () => [] },
    data: { type: Object, default: () => ({}) as UserDeptListTypes.IResponse },
  })

  const emits = defineEmits(['update:visible', 'success'])

  const visible = computed({
    get: () => props.visible,
    set: (val: boolean) => emits('update:visible', val),
  })

  watch(
    () => visible.value,
    async (newVal, oldVal) => {
      if (newVal && !oldVal) {
        await initData()
        initResult()
      }
    },
  )

  /** 查询条件 */
  const searchParam = reactive<PositionListTypes.IRequest>({ companyId, positionName: '' })

  /** 表格列配置 */
  const columns = [
    { title: '岗位', dataIndex: 'positionName' },
    { title: '操作', key: 'action' },
  ]

  /** 表格分页hook */
  const { loading, queryList, dataList, pagination, onPaginationChange } = useQueryPagination<PositionListTypes.IRequest, PositionListTypes.IResponse[]>(searchParam, requestPositionList)

  /**
   * 初始化数据
   */
  const initData = async () => await queryList()

  /**
   * 查询
   */
  const search = () => queryList({ current: 1 })

  /** 岗位结果 */
  const results = ref<PositionListTypes.IResponse[]>([])

  /**
   * 添加岗位
   * @param record 岗位
   */
  const add = async (record: PositionListTypes.IResponse) => {
    if (results.value.findIndex((item) => item.positionId === record.positionId) > -1) return
    results.value.push(record)
  }

  /**
   * 移除岗位
   * @param i 岗位结果索引
   */
  const removeResult = (i: number) => results.value.splice(i, 1)

  /**
   * 初始化岗位
   */
  const initResult = () => {
    results.value.length = 0
    props.data.positionNames.forEach((position) => {
      const result = dataList.value.find((data) => data.positionId == position.positionId)
      result && results.value.push(result)
    })
  }

  /**
   * 确定
   */
  const onOk = async () => {
    if (results.value.length === 0) {
      message.error('请先添加岗位')
      return
    }
    const { responseCode } = await requestSavePositionUser({
      companyId,
      userId: props.data.userId,
      deptId: props.data.deptList[0].deptId,
      positionIds: results.value.map((item) => item.positionId),
    })
    if (responseCode === HttpCodeEnum.SUCCESS) {
      message.success('设置成功')
      visible.value = false
      emits('success')
    }
  }
</script>

<style lang="less" scoped>
  .title {
    position: relative;
    top: -12px;
  }

  .search {
    margin-top: 12px;
  }

  .list {
    height: 300px;
    overflow: auto;

    :deep(.ant-table) {
      td {
        padding: 8px 16px;
      }
    }
  }

  .result {
    padding-top: 12px;
    border-top: 1px solid #eee;

    .result-empty {
      color: #999;
    }
  }
</style>
